// static/js/schedule_search.js
;(function () {
    document.addEventListener('DOMContentLoaded', () => {
        const openBtn = document.getElementById('open-search-modal');
        const searchModal = new bootstrap.Modal(document.getElementById('searchModal'));
        const panel = document.getElementById('search-panel');
        const backBtn = document.getElementById('back-to-search');
        const doSearchBtn = document.getElementById('do-search');
        const batchDelCtr = document.getElementById('batch-delete-container');
        const batchDelBtn = document.getElementById('batch-delete');
        const selectAllCb = document.getElementById('select-all');
        const tbody = document.getElementById('results-body');
        const startDateIn = document.getElementById('search-start-date');
        const backIcon = backBtn.querySelector('i');
        const msgEl  = document.getElementById('searchDelMsg');

        // 打开 modal 初始为向上
        backIcon.className = 'bi bi-chevron-up';

        // 打开 Modal：重置状态并默认开始日期为今天
        openBtn.addEventListener('click', e => {
            e.preventDefault();
            backBtn.style.display = 'none';
            panel.style.display = 'block';
            batchDelCtr.style.display = 'none';
            tbody.innerHTML = '';
            selectAllCb.checked = false;
            const today = new Date().toISOString().slice(0, 10);
            startDateIn.value = today;
            searchModal.show();
        });

        function showMsg(msg) {
            msgEl.textContent = msg;
            msgEl.style.display = 'inline';
            setTimeout(() => {
                msgEl.style.display = 'none';
            }, 3000);
        }

        // 执行搜索
        doSearchBtn.addEventListener('click', async () => {
            if (!startDateIn.value) {
                startDateIn.reportValidity();
                return;
            }
            // 构造参数（同前）
            const params = new URLSearchParams();
            // 用默认值或跳过
            const sd = startDateIn.value;
            const ed = document.getElementById('search-end-date').value;
            const st = document.getElementById('search-start-time').value;
            const et = document.getElementById('search-end-time').value;
            const kw = document.getElementById('search-keywords').value.trim();
            params.append('start_date', sd);
            if (ed) params.append('end_date', ed);
            if (st) params.append('start_time', st);
            if (et) params.append('end_time', et);
            if (kw) kw.split(/\s+/).forEach(k => params.append('keyword', k));

            const res = await fetch('/api/schedules/search?' + params);
            const list = res.ok ? await res.json() : [];

            // 渲染结果
            tbody.innerHTML = '';
            list.forEach(item => {
                const wkMap = {
                    Monday: '周一',
                    Tuesday: '周二',
                    Wednesday: '周三',
                    Thursday: '周四',
                    Friday: '周五',
                    Saturday: '周六',
                    Sunday: '周日'
                };
                const cnWeek = wkMap[item.weekday] || item.weekday;
                const tr = document.createElement('tr');
                tr.innerHTML = `
                  <td><input type="checkbox" data-id="${item.id}"></td>
                  <td>
                    ${item.one_date}<br>
                    <small class="text-secondary">${cnWeek}</small>
                  </td>
                  <td>${item.start_time}-${item.end_time}</td>
                  <td>${item.student_name}</td>
                `;
                tbody.appendChild(tr);
            });

            // 切 UI：隐藏面板，显示返回和批量删除
            panel.style.display = 'none';
            batchDelCtr.style.display = 'block';
            backBtn.style.display = 'inline-block';
        });

        // 返回条件
        backBtn.addEventListener('click', () => {
            panel.style.display = 'block';
            batchDelCtr.style.display = 'none';
            backBtn.style.display = 'none';
        });

        // 全选/反选
        selectAllCb.addEventListener('change', () => {
            tbody.querySelectorAll('input[type="checkbox"]').forEach(cb => {
                cb.checked = selectAllCb.checked;
            });
        });

        // 批量删除
        batchDelBtn.addEventListener('click', async () => {
            const ids = Array.from(tbody.querySelectorAll('input[type="checkbox"]:checked'))
                .map(cb => cb.dataset.id);
            if (!ids.length) return showMsg('请先勾选要删除的记录');
            if (!confirm('确认批量删除选中排课？')) return;
            await fetch('/api/schedules/batch_delete', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ids})
            });
            // 重新搜索
            doSearchBtn.click();
        });
    });
})();
